package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"time"

	log "github.com/sirupsen/logrus"
)

// 随机生成事件ID
func GetRandomScryerEvent(u *m.User, PSend func(interface{}) error) (id int64, err error) {
	//读表
	tpl, ok := data.GetAllDatas("ScryerRewards")
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到占卜事件配置,ScryerRewards")
		return
	}
	var weightVs []data.WeightV
	for _, value := range tpl {
		adRewardT := value.(data.ScryerReward).Reward
		weightVs = append(weightVs, data.WeightV{Weight: adRewardT.Weight, Value: value.(data.ScryerReward).Id})
	}
	result, _ := utils.RandomWeightKVReturnIndex(weightVs)
	id = int64(result.Value.(uint64))
	return id, nil
}

// 奖励道具
func GiveScryerAcceptRewards(from string, u *m.User, id int64, PSend func(interface{}) error) (uProp *m.UpdateProp, resGoodsList []*m.Goods, boxResList []*m.BoxRes, err error) {
	//读表
	tpl, ok := data.Get("ScryerRewards", uint64(id))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到占卜事件配置,ScryerRewards")
		log.WithFields(log.Fields{
			"method":  "GiveScryerAcceptRewards",
			"eventid": id,
		}).Error("ScryerRewards读表失败")
		return
	}
	configInfo := tpl.(data.ScryerReward)
	if configInfo.Typ == "GetRes" || configInfo.Typ == "Ad" {
		aaaa := tpl.(data.ScryerReward).Reward
		giveGoods := make([]m.BaseKV, 0)
		giveGoods = append(giveGoods, m.BaseKV{Key: int64(aaaa.Key), Val: int64(aaaa.Value)})
		uProp, resGoodsList, boxResList, err = GiveGoodsByKvList(from, u, giveGoods, PSend)
		if err != nil {
			return
		}
		return
	}
	err = errors.NewErrcode(data.Errcode.ServerErr, "没有找到,占卜事件不是给道具的事件,ScryerRewards")
	log.WithFields(log.Fields{
		"method":  "GiveScryerAcceptRewards",
		"eventid": id,
		"Typ":     configInfo.Typ,
	}).Error("ScryerRewards--占卜事件不是给道具的事件")
	return
}

// 失去道具
func LoseScryerAcceptRewards(u *m.User, id int64) (uProp *m.UpdateProp, resGoods []*m.Goods, err error) {
	//读表
	tpl, ok := data.Get("ScryerRewards", uint64(id))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到占卜事件配置,ScryerRewards")
		log.WithFields(log.Fields{
			"method":  "GiveScryerAcceptRewards",
			"eventid": id,
		}).Error("ScryerRewards读表失败")
		return
	}

	typ := tpl.(data.ScryerReward).Typ
	if typ != "LoseRes" {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "占卜事件类型不为LoseRes,ScryerRewards")
		log.WithFields(log.Fields{
			"method":  "GiveScryerAcceptRewards",
			"eventid": id,
			"typ":     typ,
		}).Error("占卜事件类型不符合")
		return
	}
	aaaa := tpl.(data.ScryerReward).Reward
	//货币--金币
	if aaaa.Key == 220001 {
		layer := u.GetLayer()
		layerT, ok := getLayerTByTid(uint64(layer.Tid))
		if !ok {
			err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到层配置")
			return
		}
		var loseCoin int64 = int64(layerT.Costs[2].Val)
		// 玩家金币不足
		if loseCoin > u.Gold {
			loseCoin = u.Gold
		}
		item := &m.Goods{Num: loseCoin, Tid: 220001}
		resGoods = append(resGoods, item)
		uProp, _ = Cost("LoseScryerAcceptRewards", u, []m.BaseKV{m.BaseKV{Key: data.GlobalEnum.Gold, Val: loseCoin}})
		return
	}
	err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到占卜事件配置,ScryerRewards")
	log.WithFields(log.Fields{
		"method":     "GiveScryerAcceptRewards",
		"eventid":    id,
		"typ":        typ,
		"LoseResTid": aaaa.Key,
	}).Error("占卜事件没有找到该配表对应方法")
	return
}

// 天灾
func ScryerFire(u *m.User, gridIds []int64) (layer *m.Layer, err error) {
	_, err = changeGridFireStatus(u, gridIds, 0, true, nil)
	// 把玩家 格子变成焦土格子
	if err != nil {
		return nil, err
	}
	layer = CurrentLayer(u)
	return
}

// 生成占卜Buff,不负责存储更新
func GiveScryBuffRewards(u *m.User, eventId int64, scryData *m.ScryerInfoData) (err error) {
	// 读表
	tpl, ok := data.Get("ScryerRewards", uint64(eventId))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到占卜事件配置,ScryerRewards")
		log.WithFields(log.Fields{
			"method":  "GiveScryerAcceptRewards",
			"eventid": eventId,
		}).Error("ScryerRewards读表失败")
		return
	}
	// 类型判断
	if tpl.(data.ScryerReward).Typ != "Buff" {
		err = errors.NewErrcode(data.Errcode.ServerErr, "该事件不为buff奖励事件")
		log.WithFields(log.Fields{
			"method":    "GiveScryBuffRewards",
			"eventid":   eventId,
			"configTyp": tpl.(data.ScryerReward).Typ,
		}).Error("该事件不为buff奖励事件")
		return
	}
	var buffId uint64 = tpl.(data.ScryerReward).BuffId
	// 读表
	tplBuff, buffok := data.Get("ScryBuffs", uint64(buffId))
	if !buffok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该BuffId的占卜Buff配置")
		log.WithFields(log.Fields{
			"method":  "GiveScryBuffRewards",
			"eventid": eventId,
			"buffId":  buffId,
		}).Error("ScryBuffs读表失败")
		return
	}
	//赋值Buff//尝试获取一个Buff
	existBuff, findBuff := scryData.ScryBuffGet(int64(buffId))
	if findBuff == false { // 新建一个Buff
		var NewBuff m.ScryBuffInfo
		//Buff的ID处理
		NewBuff.Id = int64(buffId)
		//Val作用值处理
		NewBuff.Val = tplBuff.(data.ScryBuff).Val
		//LeftCount剩余次数处理
		NewBuff.LeftCount = int64(tplBuff.(data.ScryBuff).Count)
		//EndTime时间处理
		var HourTime int64 = int64(tplBuff.(data.ScryBuff).Time.HourTime)
		var MinuteTime int64 = int64(tplBuff.(data.ScryBuff).Time.Minute)
		if HourTime == 0 && MinuteTime == 0 {
			NewBuff.EndTime = 0
		} else {
			endT := utils.TNow()
			if HourTime > 0 {
				endHourDuration := time.Duration(HourTime) * time.Hour
				endT = endT.Add(endHourDuration)
			}
			if MinuteTime > 0 {
				endMinuteDuration := time.Duration(MinuteTime) * time.Minute
				endT = endT.Add(endMinuteDuration)
			}
			NewBuff.EndTime = endT.Unix()
		}
		// Typ结束类型处理
		if NewBuff.LeftCount > 0 && NewBuff.EndTime > 0 {
			NewBuff.Typ = 2
		} else {
			if NewBuff.LeftCount > 0 {
				NewBuff.Typ = 0
			} else {
				NewBuff.Typ = 1
			}
		}
		if NewBuff.LeftCount == 0 && NewBuff.EndTime == 0 {
			err = errors.NewErrcode(data.Errcode.ServerErr, "该BuffId的占卜Buff配置次数为0，时间为0")
			log.WithFields(log.Fields{
				"method":    "GiveScryBuffRewards",
				"eventid":   eventId,
				"buffId":    buffId,
				"LeftCount": NewBuff.LeftCount,
				"Hour":      HourTime,
				"Minute":    MinuteTime,
			}).Error("该BuffId的占卜Buff配置次数为0，时间为0")
			return
		}
		//所有新Buff的准备数据处理完毕，没有问题，准备更新到data
		scryData.ScryBuffUpsetAndUpdate(&NewBuff)
		return
	} else { // 更新一个Buff
		//Buff的id一致不需要处理
		//Val作用值一致不需要处理
		//LeftCount次数处理
		existBuff.LeftCount = (existBuff.LeftCount + int64(tplBuff.(data.ScryBuff).Count))
		//EndTime时间处理--叠加事件--更新为新的结束时间
		if existBuff.Typ == 1 || existBuff.Typ == 2 {
			var HourTime int64 = int64(tplBuff.(data.ScryBuff).Time.HourTime)
			var MinuteTime int64 = int64(tplBuff.(data.ScryBuff).Time.Minute)
			NewEndT := utils.TTime(existBuff.EndTime, 0)
			if HourTime > 0 {
				endHourDuration := time.Duration(HourTime) * time.Hour
				NewEndT = NewEndT.Add(endHourDuration)
			}
			if MinuteTime > 0 {
				endMinuteDuration := time.Duration(MinuteTime) * time.Minute
				NewEndT = NewEndT.Add(endMinuteDuration)
			}
			existBuff.EndTime = NewEndT.Unix()
		}
		// Typ结束类型一致不需要处理
		scryData.ScryBuffUpsetAndUpdate(existBuff)
		return
	}
}

// 生成占卜Buff,根据buffId，不负责存储更新
func GiveScryBuffByBuffId(u *m.User, buffId int64) (err error) {
	scryerInfo := u.GetScryerInfoData()
	// 读表
	tplBuff, buffok := data.Get("ScryBuffs", uint64(buffId))
	if !buffok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该BuffId的占卜Buff配置")
		log.WithFields(log.Fields{
			"method": "GiveScryBuffRewards",
			"buffId": buffId,
		}).Error("ScryBuffs读表失败")
		return
	}
	//赋值Buff//尝试获取一个Buff
	existBuff, findBuff := scryerInfo.ScryBuffGet(int64(buffId))
	if findBuff == false { // 新建一个Buff
		var NewBuff m.ScryBuffInfo
		//Buff的ID处理
		NewBuff.Id = int64(buffId)
		//Val作用值处理
		NewBuff.Val = tplBuff.(data.ScryBuff).Val
		//LeftCount剩余次数处理
		NewBuff.LeftCount = int64(tplBuff.(data.ScryBuff).Count)
		//EndTime时间处理
		var HourTime int64 = int64(tplBuff.(data.ScryBuff).Time.HourTime)
		var MinuteTime int64 = int64(tplBuff.(data.ScryBuff).Time.Minute)
		if HourTime == 0 && MinuteTime == 0 {
			NewBuff.EndTime = 0
		} else {
			endT := utils.TNow()
			if HourTime > 0 {
				endHourDuration := time.Duration(HourTime) * time.Hour
				endT = endT.Add(endHourDuration)
			}
			if MinuteTime > 0 {
				endMinuteDuration := time.Duration(MinuteTime) * time.Minute
				endT = endT.Add(endMinuteDuration)
			}
			NewBuff.EndTime = endT.Unix()
		}
		// Typ结束类型处理
		if NewBuff.LeftCount > 0 && NewBuff.EndTime > 0 {
			NewBuff.Typ = 2
		} else {
			if NewBuff.LeftCount > 0 {
				NewBuff.Typ = 0
			} else {
				NewBuff.Typ = 1
			}
		}
		if NewBuff.LeftCount == 0 && NewBuff.EndTime == 0 {
			err = errors.NewErrcode(data.Errcode.ServerErr, "该BuffId的占卜Buff配置次数为0，时间为0")
			log.WithFields(log.Fields{
				"method":    "GiveScryBuffRewards",
				"buffId":    buffId,
				"LeftCount": NewBuff.LeftCount,
				"Hour":      HourTime,
				"Minute":    MinuteTime,
			}).Error("该BuffId的占卜Buff配置次数为0，时间为0")
			return
		}
		//所有新Buff的准备数据处理完毕，没有问题，准备更新到data
		scryerInfo.ScryBuffUpsetAndUpdate(&NewBuff)
		return
	} else { // 更新一个Buff
		//Buff的id一致不需要处理
		//Val作用值一致不需要处理
		//LeftCount次数处理
		existBuff.LeftCount = (existBuff.LeftCount + int64(tplBuff.(data.ScryBuff).Count))
		//EndTime时间处理--叠加事件--更新为新的结束时间
		if existBuff.Typ == 1 || existBuff.Typ == 2 {
			var HourTime int64 = int64(tplBuff.(data.ScryBuff).Time.HourTime)
			var MinuteTime int64 = int64(tplBuff.(data.ScryBuff).Time.Minute)
			NewEndT := utils.TTime(existBuff.EndTime, 0)
			if HourTime > 0 {
				endHourDuration := time.Duration(HourTime) * time.Hour
				NewEndT = NewEndT.Add(endHourDuration)
			}
			if MinuteTime > 0 {
				endMinuteDuration := time.Duration(MinuteTime) * time.Minute
				NewEndT = NewEndT.Add(endMinuteDuration)
			}
			existBuff.EndTime = NewEndT.Unix()
		}
		// Typ结束类型一致不需要处理
		scryerInfo.ScryBuffUpsetAndUpdate(existBuff)
		return
	}
}
